extends Area2D

signal hit

@export var speed = 400

var screep_size 
# 保存点击到的位置
var target = Vector2()

# Called when the node enters the scene tree for the first time.
func _ready():
	screep_size = get_viewport_rect().size
	pass # Replace with function body.


func _process(delta):
	var velocity = Vector2.ZERO

	#通过键盘输入移动
	if Input.is_action_pressed("move_right"):
		velocity.x += 1
	if Input.is_action_pressed("move_left"):
		velocity.x -= 1
	if Input.is_action_pressed("move_up"):
		velocity.y -= 1
	if Input.is_action_pressed("move_down"):
		velocity.y += 1
		
	if velocity.length() > 0:
		velocity = velocity.normalized() * speed
		$AnimatedSprite2D.play()
	else :
		$AnimatedSprite2D.stop()
		
	position += velocity * delta
	position.x = clamp(position.x,0,screep_size.x)
	position.y = clamp(position.y,0,screep_size.y)
	
	if velocity.x != 0:
		$AnimatedSprite2D.animation = "walk"
		$AnimatedSprite2D.flip_v = false
		$AnimatedSprite2D.flip_h = velocity.x < 0
	elif velocity.y != 0:
		$AnimatedSprite2D.animation = "up"
		$AnimatedSprite2D.flip_v = velocity.y > 0



func _on_Player_body_entered(body):
	hide()
	emit_signal("hit")
	#碰撞只需要触发一次，设置形状不被检测
	$CollisionShape2D.set_deferred("disabled", true)
	pass

# 开始游戏
func start(pos):
	position = pos
	show()
	$CollisionShape2D.set_deferred("disabled", false)
	
	
